package com.jay.net.clazz.socket;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

public class ConcurrentTCPClient implements Runnable {
	public static final int BUFFER_SIZE = 128 * 1024;// 128k
	public static final int TIMEOUT = 30 * 1000; // 30s
	Socket socket;

	public ConcurrentTCPClient(String host, int port) throws IOException {
		this.socket = new Socket();
		// Set receive buffer size before connecting
		socket.setReceiveBufferSize(BUFFER_SIZE);
		// connect to target
		socket.connect(new InetSocketAddress(host, port));
		// Set send buffer size and read timeout
		socket.setSendBufferSize(BUFFER_SIZE);
		socket.setSoTimeout(TIMEOUT);
	}

	public void run() {
		try {
			// prepare to send request
			OutputStream out = new BufferedOutputStream(
					socket.getOutputStream(), BUFFER_SIZE);
			// send request data, not shown …
			// flush request
			out.flush();
			// prepare to read reply
			InputStream in = new BufferedInputStream(socket.getInputStream(),
					BUFFER_SIZE);
			// receive reply & process it, not shown …
		} catch (IOException e) {
			/* … */
		} finally {
			try {
				if (socket != null)
					socket.close();
			} catch (IOException e) {
				// ignored
			}
		} // end finally
	} // end run()
} // end class
